package com.bawei.common.core.utils.thread;


import com.bawei.common.core.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;


/**
 * @author 蒋柏林
 * @version 1.0
 * @project mall-cloud
 * @date 2022/10/20 15:50:42
 */
@Component
public class ThreadPool {

    @Autowired
    private static ThreadPool threadPool;

    public static ThreadPool getThreadPool() {
        if(threadPool == null){
            threadPool = SpringUtils.getBean(ThreadPool.class);
        }
        return threadPool;
    }



    /**
     *  日志
     */
    private final static Logger log = LoggerFactory.getLogger(ThreadPool.class);

    /**
     * 创建数据型缓冲等待队列
     */
   private BlockingQueue<Runnable> bq =  new ArrayBlockingQueue<Runnable>(20);
    /**
     * ThreadPoolExecutor (自定义线程池) :池中运行的线程数，允许最大挂起的线程数，线程销毁时间
     */
    private ThreadPoolExecutor tpe = null;

    //定长线程池，支持定时及周期性任务执行——定期执行
    ScheduledExecutorService stp = null;

    @PostConstruct
    public void init(){
        long startTime = System.currentTimeMillis();
        log.info("线程池初始化开始");
        tpe = new ThreadPoolExecutor(2,
                50,60, TimeUnit.SECONDS,bq);
        stp = Executors.newScheduledThreadPool(1);
        log.info("线程池初始化结束,耗时：[{}MS]",System.currentTimeMillis()-startTime);
    }

    /**
     * 执行
     */
    public void execute(Runnable runnable){
        tpe.execute(runnable);
    }

    /**
     * 延迟执行 单位秒
     */
    public void delayExecute(long time,Runnable runnable){
        stp.schedule(runnable, time, TimeUnit.SECONDS);
    }
}
